package io.renren.modules.user.service.impl;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.SnowFlake;
import io.renren.modules.user.dao.UserStudentDao;
import io.renren.modules.user.dao.UserTeacherDao;
import io.renren.modules.user.service.UserStudentService;
import io.renren.modules.user.service.UserTeacherService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserTeacherServiceImpl implements UserTeacherService {
    @Autowired
    private UserTeacherDao userTeacherDao;

    @Transactional(rollbackFor = Exception.class)//加事务锁
    @Override
    public void addUser(Map<String, Object> data) {
        SnowFlake snowFlake = new SnowFlake(3L,10L);
        String teacherId =snowFlake.nextId()+"";
        data.put("userId",teacherId);
        data.put("roleId",1);
        data.put("TeacherId",teacherId);
        String salt = RandomStringUtils.randomAlphanumeric(20);
        String password = new Sha256Hash(data.get("password")+"",salt).toHex();
        data.put("salt",salt);
        data.put("password",password);
        data.put("date",new Date());
        userTeacherDao.addUser(data);
        userTeacherDao.role(data);
        userTeacherDao.teacherBindUser(data);
    }

    @Override
    public Map<String, Object> queryInfo(String userId) {
        Map<String, Object> result = userTeacherDao.queryInfo(userId);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)//加事务锁
    @Override
    public void updateUser(Map<String, Object> data) {
        String salt = RandomStringUtils.randomAlphanumeric(20);
        String password = new Sha256Hash(data.get("password")+"",salt).toHex();
        data.put("salt",salt);
        data.put("password",password);
        userTeacherDao.updateUser(data);
        userTeacherDao.updateTeacher(data);
    }
    /*
    获得用户列表
     */
    @Override
    public PageUtils queryList(Map<String, Object> param) {
        List<Map<String, Object>> list = userTeacherDao.queryList(param);
        int total = userTeacherDao.queryTotal(param);
        int limit = Integer.parseInt(param.get("limit").toString());
        int page = Integer.parseInt(param.get("page").toString());
        PageUtils pageUtils = new PageUtils(list,total,limit,page);
        return pageUtils;
    }


}
